package com.example.service;

import com.example.mapper.SysPermissionMapper;
import com.example.mapper.SysRolePermissionMapper;
import com.example.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Author: ChenZhiXiang
 * @Date: 2019/8/30 11:56
 * @Description:
 */
@Service("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysUserRoleService userRoleService;

    @Autowired
    private SysRolePermissionMapper rolePermissionMapper;

    @Autowired
    private SysPermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username){
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        // 从数据库中取出用户信息
        SysUser user = userService.selectByName(username);
        // 判断用户是否存在
        if(user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        // 添加权限
        List<SysUserRole> userRoles = userRoleService.listByUserId(user.getId());
        for (SysUserRole sysUserRole : userRoles){
            SysRole sysRole = roleService.selectById(sysUserRole.getRoleId());
            // 查出角色与权限的关联
            List<SysRolePermission> rolePermissions = rolePermissionMapper.listByRoleId(sysRole.getId());
            for (SysRolePermission rolePermission : rolePermissions) {
                // 根据权限编码查询权限
                SysPermission permission = permissionMapper.selectById(rolePermission.getPermissionId());
                authorities.add(new SimpleGrantedAuthority(permission.getName()));
            }
        }
        return new User(user.getName(),user.getPassword(),true,true,true,true,authorities);
    }
}
